<template>
  <div class="service_message">
    <el-tabs
      v-model="activeName"
      @tab-click="handleClick"
    >
      <el-tab-pane
        label="短信管理设置"
        name="set"
      >
        <div class="flex top">
          <div class="flex-1 left flex align-center justify-center">
            <p>
              1. 提醒消费者确认收货，货款到账时间最多缩短93%<br>
              2. 发货、派送、签收、退款提醒，减少物流纠纷提升购物体验<br>
              3. 催收短信提醒，提醒用户缴纳租金，缩短租金到账时间<br>
              4. 收到用户投诉短信提醒，快速得知消息解决纠纷问题<br>
            </p>
            <span>
              <img
                style="width:272px;height:148px"
                src="../../assets/images/dialog.png"
                alt=""
              >
            </span>
          </div>
          <div class="right">
            <p class="flex flex-between align-center">
              <span style="font-size:20px">短信账户</span>
              <span
                class="blue-font pointer"
                @click="checkRecords"
              >购买记录</span>
            </p>
            <p
              class="flex flex-between align-center"
              style="margin:15px 0 10px"
            >
              <span class="color-666">短信余量</span>
              <span class="color-666">{{ sms_num }}条</span>
            </p>
            <el-button
              class="w-100"
              type="primary"
              style="font-size:18px"
              @click="toBuy"
            >去购买</el-button>
            <el-divider />
            <p class="flex flex-between align-center">
              <span class="color-666">自动充值（{{ sms_automatic==1?'已开启':'未开启' }}）</span>
              <span
                class="blue-font pointer"
                @click="autoRecharge"
              >{{ sms_automatic==1?'关闭':'开启' }}</span>
            </p>
            <el-tag
              class="w-100 text-center"
              type="warning"
            >开启自动充值避免数量不足而短信无法提醒</el-tag>
          </div>
        </div>
        <div style="border: 1px solid #E6E6E6;padding:0 20px 20px;margin-top:20px">
          <h5 class="record_header">短信功能开通管理</h5>
          <p
            class="flex flex-between-center"
            style="margin-bottom:10px"
          >
            <span style="font-size:12px">供应商短信提醒</span>
            <el-button
              v-if="$hasMethod('#set')"
              size="small"
              type="primary"
              @click="openSet(null,1)"
            >批量设置</el-button>
          </p>
          <el-row :gutter="20">
            <template v-for="item in shoper_sms">
              <el-col
                :key="item.id"
                :span="6"
              >
                <div class="sms_item">
                  <div class="flex flex-between-center header">
                    <p class="flex align-center">
                      <span class="tag">{{ item.is_charge==1?'免费':'收费' }}</span>
                      <span style="margin-left:5px">{{ item.sms_title }}</span>
                    </p>
                    <span
                      class="open_icon pointer"
                      :class="item.is_open==1?'green':'red'"
                      @click="openSet(item.id)"
                    >{{ item.is_open==1?'已开启':'未开启' }}</span>
                  </div>
                  <p
                    class="color-666"
                    style="line-height:23px;font-size:12px"
                  >{{ item.trigger_rule }}</p>
                </div>
              </el-col>
            </template>
          </el-row>
          <p
            class="flex flex-between-center"
            style="margin-bottom:10px"
          >
            <span style="font-size:12px">消费者短信提醒</span>
            <el-button
              v-if="$hasMethod('#set')"
              size="small"
              type="primary"
              @click="openSet(null,2)"
            >批量设置</el-button>
          </p>
          <el-row :gutter="20">
            <template v-for="item in user_sms">
              <el-col
                :key="item.id"
                :span="6"
              >
                <div class="sms_item">
                  <div class="flex flex-between-center header">
                    <p class="flex align-center">
                      <span class="tag">{{ item.is_charge==1?'免费':'收费' }}</span>
                      <span style="margin-left:5px">{{ item.sms_title }}</span>
                    </p>
                    <span
                      class="open_icon pointer"
                      :class="item.is_open==1?'green':'red'"
                      @click="openSet(item.id)"
                    >{{ item.is_open==1?'已开启':'未开启' }}</span>
                  </div>
                  <p
                    class="color-666"
                    style="line-height:23px;font-size:12px"
                  >{{ item.trigger_rule }}</p>
                </div>
              </el-col>
            </template>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane
        label="短信发送记录"
        name="record"
      >
        <div class="warn-box">
          <svg-icon
            style="margin-right: 17px"
            icon-class="warn"
            :size="20"
          />
          <p>短信内容每超过60个字将额外使用一条短信。</p>
        </div>
        <div class="common_form_search">
          <el-form
            ref="searchForm"
            :inline="true"
            :model="searchForm"
          >
            <el-form-item label="手机号">
              <el-input
                v-model="searchForm.mobile"
                maxlength="11"
                placeholder="请输入手机号"
                clearable
                @input="val=>changeNumberInput(val)"
              />
            </el-form-item>
            <el-form-item label="发送场景">
              <el-select
                v-model="searchForm.template_id"
                style="width:230px"
                placeholder="请选择发送场景"
                clearable
              >
                <el-option
                  v-for="item in templateList"
                  :key="item.id"
                  :label="item.sms_title"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="短信状态">
              <el-select
                v-model="searchForm.send_status"
                placeholder="全部"
                clearable
              >
                <el-option
                  label="发送成功"
                  :value="1"
                />
                <el-option
                  label="发送失败"
                  :value="2"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="发送时间">
              <my-date-picker ref="myDatePicker" />
            </el-form-item>
            <el-form-item>
              <el-button
                size="small"
                type="primary"
                @click="search()"
              >查询</el-button>
              <el-button
                size="small"
                @click="reset()"
              >重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="flex align-center table-top-btns">
          <h5 class="flex align-center">
            <svg-icon
              style="margin-right:15px"
              icon-class="list"
              :size="15"
            />数据列表
          </h5>
        </div>
        <el-table
          :data="tableData"
          border
        >
          <el-table-column
            align="center"
            prop="id"
            width="80"
            label="ID"
          />
          <el-table-column
            align="center"
            width="190"
            label="关联订单号"
          >
            <template slot-scope="scope">
              <span
                class="blue-font pointer"
                @click="goToOrder(scope.row.order_id)"
              >{{ scope.row.order_id }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="sms_title"
            width="220"
            label="发送场景"
          />
          <el-table-column
            align="center"
            prop="content"
            label="短信内容"
          />
          <el-table-column
            align="center"
            prop="charging_num"
            width="100"
            label="计费数量"
          />
          <el-table-column
            align="center"
            prop="username"
            width="100"
            label="发送人"
          />
          <el-table-column
            align="center"
            label="短信状态"
            width="100"
          >
            <template slot-scope="scope">
              <span
                class="status_icon"
                :class="{'success':scope.row.send_status==1}"
              >{{ scope.row.send_status_name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="reason"
            label="原因"
            width="200"
          />
          <el-table-column
            align="center"
            prop="create_time"
            width="160"
            label="发送时间"
          />
        </el-table>
        <custom-page
          ref="customPage"
          :total="total"
          @getList="getData"
        />
      </el-tab-pane>
      <!-- <el-tab-pane label="群发短信" name="allUser">
        <div>
          <el-form ref="allUserform" label-width="50" inline :model="allUserform">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="allUserform.name" placeholder="请输入姓名" style="width:150px" clearable />
            </el-form-item>
            <el-form-item label="省份" prop="prov">
              <el-input v-model="allUserform.prov" placeholder="请输入省份" style="width:150px" clearable />
            </el-form-item>
            <el-form-item label="城市" prop="city">
              <el-input v-model="allUserform.city" placeholder="请输入城市" style="width:150px" clearable />
            </el-form-item>
            <el-form-item label="地区" prop="area">
              <el-input v-model="allUserform.area" placeholder="请输入地区" style="width:150px" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="searchBtn" @click="allUsersearch()">
                查询
              </el-button>
              <el-button class="resetBtn" @click="resetallUserSearch()">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="btnGroup">
          <el-button class="resetBtn" @click="sendMsgShow('1')">
            全部发送
          </el-button>
          <el-button class="resetBtn" @click="sendMsgShow('2')">
            选择发送
          </el-button>
        </div>
        <div class="table-container">
          <el-table :data="adviceList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="名称" align="center" prop="name" />
            <el-table-column label="手机号" align="center" prop="phone" />
            <el-table-column label="省份" align="center" prop="prov" />
            <el-table-column label="城市" align="center" prop="city" />
            <el-table-column label="地区" align="center" prop="area" />
            <el-table-column label="详细地址" align="center" prop="address" />
          </el-table>
          <custom-page
            ref="allUserPage"
            :total="allUsertotal"
            @getList="getAllUserInfo"
          />
        </div>
      </el-tab-pane> -->
    </el-tabs>
    <buy-dialog
      ref="buyDialog"
      dialog-title="短信购买"
      :type="2"
      @getList="getData"
    />
    <recharge-dialog
      ref="rechargeDialog"
      :type="2"
      dialog-title="短信自动充值"
      @getList="getData"
    />
    <set-dialog
      ref="setDialog"
      :multiple="multiple"
      :sms-type="smsType"
      :select-id="selectId"
      @getList="getData"
    />
    <el-dialog
      :modal-append-to-body="false"
      title="输入发送内容"
      class="dialogClass"
      :visible.sync="dialogVisible"
      width="500px"
    >
      <el-form ref="dynamicValidateForm" :model="dynamicValidateForm" style="width:350px;margin: 0 auto;">
        <el-form-item prop="content" label="短信内容">
          <el-input v-model="dynamicValidateForm.content" type="textarea" :rows="2" placeholder="请输入内容" clearable />
        </el-form-item>
        <el-form-item label-width="0px" style="margin: 8px auto;text-align: center">
          <el-button type="primary" class="login-btn" @click="sendEmail">发送
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { smsRemind, autoRecharge, getSmsTemplate, smsRecord, getRealList, sendAllUser } from '@/api/marketing'
import buyDialog from './components/buy'
import rechargeDialog from './components/recharge'
import setDialog from './components/set'
import myDatePicker from '@/components/myDatePicker'
import customPage from '@/components/customPage'
export default {
  components: { buyDialog, rechargeDialog, setDialog, myDatePicker, customPage },
  data() {
    return {
      activeName: 'set',
      sms_num: 0,
      sms_automatic: 0,
      shoper_sms: [],
      user_sms: [],
      smsType: 1,
      selectId: '',
      multiple: false,
      searchForm: {
        mobile: '',
        template_id: '',
        send_status: '',
        create_time: ''
      },
      templateList: [],
      tableData: [],
      total: 0,
      allUsertotal: 0,
      allUserform: [],
      multipleSelection: [],
      adviceList: [],
      dynamicValidateForm: {
        content: ''
      },
      sendType: '',
      dialogVisible: false
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    goToOrder(orderId) {
      if (orderId) {
        this.$router.push({ name: 'orderList', params: { orderId }})
      }
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val
    },
    getAllUserInfo() {
      const { page, pageSize } = this.$refs.allUserPage
      getRealList({ page, pageSize, ...this.allUserform }).then(res => {
        const { data, total } = res
        this.adviceList = data || []
        this.allUsertotal = total || 0
      })
    },
    allUsersearch() {
      this.getAllUserInfo()
    },
    resetallUserSearch() {
      this.allUserform = []
      this.getAllUserInfo()
    },
    sendMsgShow(type) {
      this.sendType = type
      if (type == '2' && this.multipleSelection.length == 0) {
        this.$message({
          showClose: true,
          message: '发送对象不能为空！！！',
          type: 'error'
        })
      } else {
        this.dialogVisible = true
      }
    },
    sendEmail: function() {
      this.$refs['dynamicValidateForm'].validate((valid) => {
        if (valid && this.dynamicValidateForm.content != '') {
          var data = null
          if (this.sendType == '1') {
            data = {
              content: this.dynamicValidateForm.content
            }
          } else {
            const aaa = this.multipleSelection.map(k => { return { 'phone': k.phone } })
            debugger
            data = {
              users: aaa,
              content: this.dynamicValidateForm.content
            }
          }
          sendAllUser(data).then((res) => {
            console.log(res)
            var msg = '发送成功：' + res.successful + '个，发送失败：' + res.error + '个'
            this.dynamicValidateForm.content = ''
            this.dialogVisible = false
            this.$notify({
              title: '发送短信',
              message: msg,
              duration: 0
            })
          })
        } else {
          this.dynamicValidateForm.content = ''
          console.log('error send!!')
          return false
        }
      })
    },

    changeNumberInput(value) {
      const pattern = /^[1-9][0-9]*$/
      if (!pattern.test(value)) {
        // input 框绑定的内容为空
        this.searchForm.mobile = ''
      }
    },
    openSet(id, type) {
      if (!this.$hasMethod('#set') && id) {
        return
      }
      if (id) {
        this.multiple = false
        this.selectId = id + ''
        this.smsType = 1
      } else {
        this.multiple = true
        this.selectId = ''
        this.smsType = type
      }
      this.$refs.setDialog.dialogVisible = true
    },
    // 去购买
    toBuy() {
      this.$refs.buyDialog.dialogVisible = true
    },
    // 自动充值
    autoRecharge() {
      if (this.sms_automatic == 1) {
        // 关闭
        this.$confirm('确认要关闭自动充值吗?', '关闭自动充值', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          autoRecharge({
            baseline: '',
            recharge_num: '',
            recharge_type: 2,
            sms_remind: ''
          }).then(res => {
            this.getData()
          })
        }).catch(() => { })
      } else {
        // 开启
        this.$refs.rechargeDialog.dialogVisible = true
      }
    },
    // 购买记录
    checkRecords() {
      this.$router.push({ name: 'serviceMessageRecord' })
    },
    handleClick(tab, event) {
      this.getData()
    },
    // 查询
    search() {
      const pickerVal = this.$refs.myDatePicker.getVal()
      if (pickerVal !== 'error') {
        this.searchForm.create_time = pickerVal
        this.$refs.customPage.page = 1
        this.getData()
      }
    },
    // 重置
    reset() {
      if (this.$refs.myDatePicker) {
        this.$refs.myDatePicker.reset()
      }
      this.searchForm = {
        mobile: '',
        template_id: '',
        send_status: '',
        create_time: ''
      }
      this.getData()
    },
    getData() {
      if (this.activeName === 'set') {
        smsRemind().then(res => {
          const { sms_num, sms_automatic, shoper_sms, user_sms } = res
          this.sms_num = sms_num
          this.sms_automatic = sms_automatic
          this.shoper_sms = shoper_sms || []
          this.user_sms = user_sms || []
        })
      } else if (this.activeName === 'record') {
        this.getSelect()
        const { page, pageSize } = this.$refs.customPage
        smsRecord({
          page,
          pageSize,
          ...this.searchForm
        }).then(res => {
          const { data, total } = res
          this.tableData = data || []
          this.total = total || 0
        })
      } else {
        this.getAllUserInfo()
      }
    },
    getSelect() {
      getSmsTemplate().then(res => {
        this.templateList = res || []
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.top {
  height: 260px;
  .el-divider--horizontal {
    margin: 20px 0;
  }
}
.left {
  padding: 10px;
  background-color: #f5f5f5;
  & > p {
    line-height: 40px;
    margin-right: 60px;
  }
}
.right {
  width: 345px;
  margin-left: 20px;
  padding: 20px;
  border: 1px solid #e6e6e6;
  p {
    line-height: 23px;
  }
  span {
    font-size: 16px;
  }
  .el-tag {
    color: #ff8500;
    margin-top: 10px;
    font-size: 14px;
  }
}
.record_header {
  padding-left: 15px;
  border-left: 3px solid $mainBlue;
  margin: 20px 0;
}
.sms_item {
  width: 100%;
  height: 125px;
  padding: 15px;
  background: #f5f5f5;
  margin-bottom: 20px;
  .header {
    border-bottom: 1px dashed #cdcdcd;
    padding: 0 0 15px;
    margin-bottom: 10px;
  }
  .tag {
    padding: 3px;
    border: 1px solid #ff4146;
    border-radius: 3px;
    color: #ff4146;
    font-size: 12px;
    border-radius: 3px;
    min-width: 32px;
    box-sizing: border-box;
  }
}
.open_icon {
  padding: 5px;
  font-size: 12px;
  color: #ffffff;
  border-radius: 3px;
  min-width: 46px;
  box-sizing: border-box;
  &.red {
    background: #ff4146;
  }
  &.green {
    background: #4ccb86;
  }
}
@media screen and (max-width: 1420px) {
  .left > p {
    line-height: 1.8;
  }
  .sms_item {
    height: 150px;
  }
}
.status_icon::before {
  display: inline-block;
  content: "";
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #ff4146;
  margin-right: 6px;
}
.status_icon.success::before {
  background-color: #4ccb86;
}
</style>
